package com.easipass.exangeservice.msg;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-2-20
 */
public class TextFileMsg extends FileMsg implements TextMsg {

	public TextFileMsg() {}
	
	public TextFileMsg(Msg msg) {
		copyAttributesFrom(msg);
	}
	
	public TextFileMsg(FileMsg fileMsg, String encoding) {
		copyAttributesFrom(fileMsg);
		setEncoding(encoding);
	}

	public TextFileMsg(File f, String encoding) throws IOException {
		super(f);
		setEncoding(encoding);
	}
	
	public static TextFileMsg copyTextMsg(TextMsg textMsg) throws IOException {
		TextFileMsg m = new TextFileMsg();
		m.copyAttributesFrom(textMsg);
		copyRawData(textMsg, m, -1);
		return m;
	}
	
	public static TextFileMsg copyRawMsg(RawMsg rawMsg, String encoding) throws IOException {
		TextFileMsg m = new TextFileMsg();
		m.copyAttributesFrom(rawMsg);
		copyRawData(rawMsg, m, -1);
		m.setEncoding(encoding);
		return m;
	}
	
	public String getEncoding() {
		return getAttribute(ATTR_ENCODING);
	}

	public void setEncoding(String encoding) {
		setAttribute(ATTR_ENCODING, encoding);
	}
	
	public Reader openReader() throws IOException {
		InputStream in = openInputStream();
		if(in == null) return null;
		String encoding = getEncoding() == null ? "UTF-8" : getEncoding();
		Charset c = Charset.forName(encoding);
		return new InputStreamReader(in, c);
	}

	public Writer openWriter() throws IOException {
		OutputStream out = openOutputStream();
		if(out == null) return null;
		String encoding = getEncoding() == null ? "UTF-8" : getEncoding();
		Charset c = Charset.forName(encoding);
		return new OutputStreamWriter(out, c);
	}

}
